// pages/goodsXiangqing/putongGoods/putongGoods.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    leiIndex: '',
    headIndex: 0,
    goodsid: '',
    goodsinfo: '',
    quyulist: [],
    img1: '',
    img2: '',
    shareimg: '', //分享出去的图片
    isOverShare: true,
    maskdown:false
  },
  closemask() {
    this.setData({
      maskdown: false
    })
  },
  getgoodsinfo() {
    let that = this
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "tourGoodsDetails",
        shopId: wx.getStorageSync('shopId'),
        goodsId: that.data.goodsid
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        if (res.data.result == 1) {
          setTimeout(function () {
            wx.hideLoading()
          }, 0)
          setTimeout(function () {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
        } else {
          that.getimg1(res.data.goodsImg[0])
          if (res.data.goodsImg[1]) {
            that.getimg2(res.data.goodsImg[1])
          }
          let quyulist = []
          for (let i in res.data.salesArea) {
            // console.log(i)
            quyulist.push(res.data.salesArea[i])
          }
          that.setData({
            goodsinfo: res.data,
            leiIndex: res.data.state,
            quyulist: quyulist
          })
          setTimeout(function () {
            wx.hideLoading()
          }, 0)
        }
      }
    });
  },
  xiajiabox() {
    this.setData({
      maskdown: true
    })
  },
  // 下架商品
  toxiajia() {
    let that = this
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "lowframeGood",
        userId: wx.getStorageSync('userId'),
        goodsId: that.data.goodsid
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        that.setData({
          maskdown: false
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 0)
        setTimeout(function () {
          wx.showToast({
            title: res.data.resultNote,
            icon: 'none',
            duration: 1500
          })
        }, 0)
        if (res.data.result == 1) { } else {
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 1500)
        }
      }
    });
    // wx.showModal({
    //   title: '是否确定下架',
    //   success: function (res) {
    //     if (res.confirm) {
    //       setTimeout(function () {
    //         wx.showLoading({
    //           title: '加载中',
    //         })
    //       }, 0)
          
    //     } else {
    //       console.log('点击取消回调')
    //     }
    //   }
    // })
  },
  // 删除商品
  toshanchu() {
    let that = this
    wx.showModal({
      title: '是否确定删除商品',
      success: function (res) {
        if (res.confirm) {
          setTimeout(function () {
            wx.showLoading({
              title: '加载中',
            })
          }, 0)
          wx.request({
            url: app.globalData.myurl,
            data: {
              cmd: "delGood",
              userId: wx.getStorageSync('userId'),
              goodsId: that.data.goodsid
            },
            header: {
              "content-type": "application/x-www-form-urlencoded",
              "token": wx.getStorageSync('token')
            },
            success(res) {
              if (res.data.zjstate == 1) {
                setTimeout(function () {
                  wx.hideLoading()
                  wx.stopPullDownRefresh() //停止下拉刷新
                }, 0)
                setTimeout(function () {
                  wx.showModal({
                    title: '您的账号已在其他设备登录，请重新登录！',
                    showCancel: false, //是否显示取消按钮false去掉取消按钮
                    success: function (res) {
                      if (res.confirm) {
                        wx.clearStorageSync()
                        wx.reLaunch({
                          url: '/pages/login/login',
                        })
                      } else {
                        wx.clearStorageSync()
                        wx.reLaunch({
                          url: '/pages/login/login',
                        })
                      }
                    }
                  })
                }, 0)
                return
              }
              setTimeout(function () {
                wx.hideLoading()
              }, 0)
              setTimeout(function () {
                wx.showToast({
                  title: res.data.resultNote,
                  icon: 'none',
                  duration: 1500
                })
              }, 0)
              if (res.data.result == 1) { } else {
                setTimeout(function () {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 1500)
              }
            }
          });
        } else {
          console.log('点击取消回调')
        }
      }
    })
  },
  // 重新上架
  tochongxinSj() {
    let that = this
    wx.showModal({
      title: '是否确定重新上架',
      success: function (res) {

        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/goods/page/goodsFabu/twopinFabu/twopinFabu?goodsId=' + that.data.goodsid,
          })
          //   setTimeout(function () {
          //     wx.showLoading({
          //       title: '加载中',
          //     })
          //   }, 0)
          //   wx.request({
          //     url: app.globalData.myurl,
          //     data: {
          //       cmd: "groundGood",
          //       userId: wx.getStorageSync('userId'),
          //       goodsId: that.data.goodsid
          //     },
          //     header: {
          //       "content-type": "application/x-www-form-urlencoded"
          //     },
          //     success(res) {
          //       setTimeout(function () {
          //         wx.hideLoading()
          //       }, 0)
          //       setTimeout(function () {
          //         wx.showToast({
          //           title: res.data.resultNote,
          //           icon: 'none',
          //           duration: 1500
          //         })
          //       }, 0)
          //       if (res.data.result == 1) {
          //       } else {
          //         setTimeout(function () {
          //           wx.navigateBack({
          //             delta: 1
          //           })
          //         }, 1500)
          //       }
          //     }
          //   });
        } else {
          console.log('点击取消回调')
        }
      }
    })
  },
  // 修改商品
  toxiuGai() {
    wx.navigateTo({
      url: '/pages/goods/page/goodsFabu/twopinFabu/twopinFabu?goodsId=' + this.data.goodsid,
    })
  },
  // 重新申请上架
  tochongxinSQ() {
    let that = this
    wx.showModal({
      title: '是否重新申请',
      success: function (res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/goods/page/goodsFabu/twopinFabu/twopinFabu?goodsId=' + that.data.goodsid,
          })
        } else {
          console.log('点击取消回调')
        }
      }
    })
  },
  // 切换头部
  changeIndex(e) {
    let that = this
    console.log(e.currentTarget.dataset.index)
    that.setData({
      headIndex: e.currentTarget.dataset.index
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this

    that.setData({
      goodsid: options.goodsid,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    setTimeout(function () {
      wx.showLoading({
        title: '加载中',
      })
    }, 0)
    that.getgoodsinfo()
    var timerr = setInterval(function () {
      if (that.data.img1) {
        that.getshareimg();
        clearInterval(timerr)
      }
    }, 100)

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    var shareimg = that.data.shareimg;
    return {
      path: "/pages/shopping/huopinxq/huopinxq?goodsid=" + that.data.goodsinfo.goodsId + '&type=5',
      imageUrl: shareimg,
      title: wx.getStorageSync('shopName')
    };
  },
  roundRect(ctx, x, y, w, h, r, fillColor, strokeColor) {
    // 画圆角 ctx、x起点、y起点、w宽度、y高度、r圆角半径、fillColor填充颜色、strokeColor边框颜色
    // 开始绘制
    ctx.beginPath()

    // 绘制左上角圆弧 Math.PI = 180度
    // 圆心x起点、圆心y起点、半径、以3点钟方向顺时针旋转后确认的起始弧度、以3点钟方向顺时针旋转后确认的终止弧度
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)

    // 绘制border-top
    // 移动起点位置 x终点、y终点
    ctx.moveTo(x + r, y)
    // 画一条线 x终点、y终点
    ctx.lineTo(x + w - r, y)
    // ctx.lineTo(x + w, y + r)

    // 绘制右上角圆弧
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)

    // 绘制border-right
    ctx.lineTo(x + w, y + h - r)
    // ctx.lineTo(x + w - r, y + h)

    // 绘制右下角圆弧
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)

    // 绘制border-bottom
    ctx.lineTo(x + r, y + h)
    // ctx.lineTo(x, y + h - r)

    // 绘制左下角圆弧
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)

    // 绘制border-left
    ctx.lineTo(x, y + r)
    // ctx.lineTo(x + r, y)

    if (fillColor) {
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      ctx.setFillStyle(fillColor)
      // 对绘画区域填充
      ctx.fill()
    }

    if (strokeColor) {
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      ctx.setStrokeStyle(strokeColor)
      // 画出当前路径的边框
      ctx.stroke()
    }
    // 关闭一个路径
    // ctx.closePath()

    // 剪切，剪切之后的绘画绘制剪切区域内进行，需要save与restore
    ctx.clip()
  },
  getshareimg() {
    console.log(11111111111111111111111111)
    var _this = this;
    var type = this.data.type;
    var info = this.data.goodsinfo;
    var imglist = info.goodsImg;
    const ctx = wx.createCanvasContext('shareimg')
    console.log(imglist)
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, 250, 200);
    // 商品名称
    ctx.fillStyle = "#333";
    ctx.setFontSize(18)
    var str = info.goodsName;
    if (str.length > 13) {
      str = str.substring(0, 13) + "...";
    }
    ctx.fillText(str, 10, 150)

    var img1 = this.data.img1;
    var img2 = this.data.img2;
    ctx.drawImage(img1, 10, 10, 110, 110)
    if (img2) {
      ctx.drawImage(img2, 135, 10, 110, 110)
    }
    ctx.fillStyle = "#E22405";
    ctx.setFontSize(16)
    ctx.fillText("￥", 10, 185)




    ctx.setFontSize(22)
    var moneywidth;
    
      ctx.fillText(String(info.goodSkuList[0].costprice) + '/' + info.goodsUnit, 24, 185)
      moneywidth = ctx.measureText(String(info.goodSkuList[0].costprice)).width
    
    // // console.log(moneywidth)
    ctx.setFontSize(12)
    var discountText;
    
      discountText = '2人团'
    
    var bdColor = '#E22405';
    var bdBackground = 'transparent';
    var bdRadius = 4;
    var textPadding = 6;
    var boxHeight = 18;
    var boxWidth = ctx.measureText(discountText).width + textPadding * 2;
    ctx.fillText(discountText, moneywidth + 75, 183);
    this.roundRect(ctx, moneywidth + 70, 169, boxWidth, boxHeight, bdRadius, bdBackground, bdColor)



    ctx.draw()
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'shareimg',
        success(res) {
          console.log(res.tempFilePath)
          _this.setData({
            shareimg: res.tempFilePath
          })
        }
      })
    }, 500)


  },
  getimg1(imgurl) {
    var _this = this;
    wx.downloadFile({
      url: imgurl, //仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          // console.log(res.tempFilePath)
          _this.setData({
            img1: res.tempFilePath,
          })
        }
      }
    })
  },
  getimg2(imgurl) {
    // console.log(imgurl)
    var _this = this;
    wx.downloadFile({
      url: imgurl, //仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          _this.setData({
            img2: res.tempFilePath,
          })
        }
      }
    })
  },
})